import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:old_shop/common/appbar/appbar.dart';
import 'package:old_shop/common/const/cosnt.dart';
import 'package:zevent_bus/zevent_bus.dart';

class AutoBuy extends StatefulWidget {
  @override
  State<AutoBuy> createState() => _AutoBuyState();
}

class _AutoBuyState extends State<AutoBuy> with AutomaticKeepAliveClientMixin {
  List<dynamic> data = [];
  VoidCallback? listener;
  num money = 0;
  bool isSelectAll = false;
  @override
  void initState() {
    super.initState();
    EventBus.instance.addListener(
      eventKey: 'add',
      callback: (arg) {
        setState(() {
          data.add(arg);
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: NormalAppbar.normal(
        title: "购物车",
        leading: const SizedBox(),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.separated(
              padding: const EdgeInsets.all(12),
              separatorBuilder: (_, __) => Divider(),
              itemBuilder: (context, index) {
                if (data.isEmpty)
                  return Column(
                    children: [
                      SizedBox(height: MediaQuery.of(context).size.height * 0.3),
                      Icon(
                        Icons.image_search,
                        color: Colors.grey[400],
                        size: 50,
                      ),
                      const SizedBox(height: 8),
                      Text(
                        "空空如也,去首页看看吧~",
                        style: TextStyle(color: Colors.grey),
                      )
                    ],
                  );
                return _Cell(
                  model: data[index],
                );
              },
              itemCount: data.isEmpty ? 1 : data.length,
            ),
          ),
          _Bottom(
            isselectall: isSelectAll,
            count: data.length,
            totalMoney: money,
            onSelectAll: () {
              money = 0;
              isSelectAll = !isSelectAll;
              if (isSelectAll) {
                data.forEach((element) {
                  money += element["height"] ~/ 100;
                });
              }

              setState(() {});
            },
          ),
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class _Cell extends StatelessWidget {
  final Map<String, dynamic> model;

  const _Cell({super.key, required this.model});
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Container(
          width: 100,
          height: 80,
          margin: const EdgeInsets.only(right: 12),
          child: PhysicalModel(
            borderRadius: BorderRadius.circular(12),
            clipBehavior: Clip.antiAlias,
            color: Colors.transparent,
            child: CachedNetworkImage(
              imageUrl: model["download_url"],
              fit: BoxFit.cover,
            ),
          ),
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              model["author"],
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, height: 28 / 18),
            ),
            Text(
              "\$${model["height"] ~/ 100}",
              style: TextStyle(fontWeight: FontWeight.bold, color: Colors.redAccent, fontSize: 18, height: 28 / 18),
            ),
          ],
        )
      ],
    );
  }
}

class _Bottom extends StatelessWidget {
  final bool isselectall;
  final Function()? onTap;
  final num? totalMoney;
  final int? count;
  final Function()? onSelectAll;
  const _Bottom({Key? key, this.count, this.isselectall = false, this.onSelectAll, this.totalMoney, this.onTap})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 7),
      margin: EdgeInsets.only(bottom: 3),
      child: Row(
        children: [
          InkWell(
            onTap: onSelectAll,
            child: Row(
              children: [
                Icon(
                  isselectall ? Icons.check_circle : Icons.circle_outlined,
                  color: AppColor.mainColor,
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 4.0, right: 4),
                  child: Text(
                    "全选",
                    style: AppFont.textStyle(12),
                  ),
                ),
              ],
            ),
          ),
          Text(
            "合计：￥${totalMoney ?? 0}",
            style: AppFont.textStyle(12),
          ),
          Spacer(),
          InkWell(
            onTap: onTap,
            child: Container(
              width: 100,
              height: 36,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(30),
                  gradient: LinearGradient(colors: [const Color(0xffE5C75A), const Color(0xff976F1C)])),
              child: Text(
                "结算(${count ?? 0})",
                style: AppFont.textStyle(14, color: Colors.white),
              ),
            ),
          )
        ],
      ),
    );
  }
}
